package com.ithao.security;

import com.ithao.common.GlobalConst;
import com.ithao.pojo.User;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author : ZhangHao
 * @version :1.0
 * @date :Created in 2020/4/18
 * @description :
 */
@WebFilter("/*")
@Slf4j
public class AuthFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取拦截的路径 如： /pages/welcome.html
        String path = request.getServletPath();
        log.info("[AuthFilter] 拦截url :{}", path);


        //如果是登录就直接放行
        if ("/login.html".equals(path) || "/user/login.do".equals(path)) {
            filterChain.doFilter(request, response);
            return;
        }
        //获取浏览器Session的user
        if (path.endsWith(".html") || path.contains(".do")) {
            User user = (User) request.getSession().getAttribute(GlobalConst.SESSION_KEY_USER);
            if (null == user) {
                log.warn("未登录，请先登录。。。");
                response.sendRedirect(request.getContextPath() + "/login.html");
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
